<?php

declare(strict_types=1);
/**
 * This file is part of MoChat.
 * @link     https://mo.chat
 * @document https://mochat.wiki
 * @contact  group@mo.chat
 * @license  https://github.com/mochat-cloud/mochat/blob/master/LICENSE
 */
namespace MoChat\App\Tenant\Service;

use Hyperf\Database\Model\Builder;
use MoChat\App\Tenant\Contract\TenantContract;
use MoChat\App\Tenant\Model\Tenant;
use MoChat\Framework\Service\AbstractService;
use MoChat\Plugin\TenantProduct\Model\TenantProductSku;

class TenantService extends AbstractService implements TenantContract
{
    /**
     * @var Tenant
     */
    protected $model;

    /**
     * 查询单条 - 根据ID.
     * @param int $id ID
     * @param array|string[] $columns 查询字段
     * @return array 数组
     */
    public function getTenantById(int $id, array $columns = ['*']): array
    {
        return $this->model->getOneById($id, $columns);
    }

    /**
     * 查询多条 - 根据ID.
     * @param array $ids ID
     * @param array|string[] $columns 查询字段
     * @return array 数组
     */
    public function getTenantsById(array $ids, array $columns = ['*']): array
    {
        return $this->model->getAllById($ids, $columns);
    }

    /**
     * 多条分页.
     * @param array $where 查询条件
     * @param array|string[] $columns 查询字段
     * @param array $options 可选项 ['orderByRaw'=> 'id asc', 'perPage' => 15, 'page' => null, 'pageName' => 'page']
     * @return array 分页结果 Hyperf\Paginator\Paginator::toArray
     */
    public function getTenantList(array $where, array $columns = ['*'], array $options = []): array
    {
        return $this->model->getPageList($where, $columns, $options);
    }

    /**
     * 添加单条
     * @param array $data 添加的数据
     * @return int 自增ID
     */
    public function createTenant(array $data): int
    {
        return $this->model->createOne($data);
    }

    /**
     * 添加多条
     * @param array $data 添加的数据
     * @return bool 执行结果
     */
    public function createTenants(array $data): bool
    {
        return $this->model->createAll($data);
    }

    /**
     * 修改单条 - 根据ID.
     * @param int $id id
     * @param array $data 修改数据
     * @return int 修改条数
     */
    public function updateTenantById(int $id, array $data): int
    {
        return $this->model->updateOneById($id, $data);
    }

    /**
     * 修改多条 - 根据ID.
     * @param array $data 修改数据
     * @return int 修改条数
     */
    public function updateTenantsById(array $ids, array $data): int
    {
        return $this->model::query()->whereIn('id', $ids)->update($data);
    }

    /**
     * 删除 - 单条
     * @param int $id 删除ID
     * @return int 删除条数
     */
    public function deleteTenant(int $id): int
    {
        return $this->model->deleteOne($id);
    }

    /**
     * 删除 - 多条
     * @param array $ids 删除ID
     * @return int 删除条数
     */
    public function deleteTenants(array $ids): int
    {
        return $this->model->deleteAll($ids);
    }

    /**
     * {@inheritdoc}
     */
    public function getTenantByStatus(): array
    {
        $data = $this->model::query()->where('status', 1)->first();
        if (! $data) {
            return [];
        }
        return $data->toArray();
    }

    /**
     * 查询单条 - 根据ID.
     * @param array|string[] $columns 查询字段
     * @return null|Builder|\Hyperf\Database\Model\Model|object 数组
     */
    public function getTenantByPhone(string $phone, array $columns = ['*'])
    {
        return $this->model::query()->where('phone', $phone)->first($columns);
    }

    /**
     * @param array|string[] $columns
     */
    public function getTenantListSearch(int $ownerId, int $skuId, string $phone, string $startTime, string $endTime, array $columns = ['*']): array
    {
        $res = $this->model::query()
            ->when($ownerId > 0, function (Builder $query) use ($ownerId) {
                return $query->where('owner_id', $ownerId);
            })
            ->when($skuId > 0, function (Builder $query) use ($skuId) {
                return $query->where('sku_id', $skuId);
            })
            ->when(! empty($phone), function (Builder $query) use ($phone) {
                return $query->where('name', 'like', "%{$phone}%");
            })
            ->when(! empty($startTime), function (Builder $query) use ($startTime, $endTime) {
                return $query->whereBetween('created_at', [$startTime, $endTime]);
            })
            ->orderByDesc('created_at')
            ->get($columns);
        $res || $res = collect([]);

        return $res->toArray();
    }

    /**
     * 软删除查询.
     * @param array|string[] $columns
     */
    public function getTenantByIdWithTrashed(int $id, array $columns = ['*']): array
    {
        $res = $this->model::query()
            ->where('id', $id)
            ->withTrashed()
            ->first($columns);
        $res || $res = collect([]);
        return $res->toArray();
    }

    /**
     * 查询租户数量.
     */
    public function countTenantByOwnerId(array $ownerIds, string $startTime, string $endTime, int $type = 0): int
    {
        return $this->model::from($this->model::query()->getModel()->getTable() . ' as tenant')
            ->join(TenantProductSku::query()->getModel()->getTable() . ' as tenant_product_sku', 'tenant.sku_id', 'tenant_product_sku.id')
            ->where('tenant.status', 1)
            ->when(! empty($ownerIds), function (Builder $query) use ($ownerIds) {
                return $query->whereIn('tenant.owner_id', $ownerIds);
            })
            ->when(! empty($startTime), function (Builder $query) use ($startTime, $endTime) {
                return $query->whereBetween('tenant.created_at', [$startTime, $endTime]);
            })
            ->when($type > 0, function (Builder $query) use ($type) {
                if ($type === 1) {// 付费
                    return $query->where('tenant_product_sku.price', '>', 0);
                }

                if ($type === 2) {// 未付费
                    return $query->where('tenant_product_sku.price', 0);
                }
            })
            ->count('tenant.id');
    }

    /**
     * 查询多条 - 根据skuId.
     * @param array|string[] $columns 查询字段
     */
    public function getTenantBySkuId(int $skuId, array $columns = ['*']): array
    {
        $res = $this->model::query()
            ->where('sku_id', $skuId)
            ->get($columns);
        $res || $res = collect([]);
        return $res->toArray();
    }
}
